package cn.com.jcoo.example.support.redis;

import cn.com.jcoo.security.Sm4Utils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.util.StringUtils;

@Slf4j
@Aspect
@EnableAspectJAutoProxy
public class RedisPasswordAspect {
    @Value("${spring.data.redis.password}")
    private String password;
    @Autowired
    private RedisProperties redisProperties;

    /**
     * redis获取连接配置密码切点
     */
    @Pointcut("execution(* org.springframework.boot.autoconfigure.data.redis.RedisProperties.getPassword())")
    public void getRedisConnectionPwd() {
    }

    /**
     * 在切点前执行解密
     */
    @Before("getRedisConnectionPwd()")
    public void decryptRedisPassword() {
        try {
            if (!StringUtils.hasLength(password)) {
                return;
            }
            String pwd = Sm4Utils.decryptStr(password);
            log.info("redis密码:{}", pwd);
            redisProperties.setPassword(pwd);
        } catch (Exception e) {
            log.error("redis密码解密错误:{}", e.getMessage(), e);
        }
    }

    public static void main(String[] args) {
        System.out.println(Sm4Utils.encryptStr("123456"));
        System.out.println(Sm4Utils.decryptStr("RSATngy4OQzK4IUCtEMbjw=="));
    }
}
